package com.myapp.ruyixing.ui;

import java.util.ArrayList;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.myapp.ruyixing.Config;
import com.myapp.ruyixing.R;
import com.myapp.ruyixing.http.RYHttpClient;
import com.myapp.ruyixing.http.RYHttpResponseHandler;
import com.myapp.ruyixing.model.DiscountDetail;
import com.myapp.ruyixing.model.DiscountDetail.DetailItem;
import com.myapp.ruyixing.model.Model;
import com.myapp.ruyixing.model.ShopAlbum.PhotoItem;
import com.myapp.ruyixing.ui.widget.DocIndicator;
import com.myapp.ruyixing.ui.widget.PickPhoneCallFragment;
import com.myapp.ruyixing.ui.widget.VerticalScrollView;
import com.myapp.ruyixing.ui.widget.VerticalScrollView.OnScrollChangedListener;
import com.myapp.ruyixing.utils.BitmapLruCache;
import com.myapp.ruyixing.utils.LoginHelper;
import com.myapp.ruyixing.utils.UIUtils;

public class DiscountDetailActivity extends BaseActivity implements
		OnScrollChangedListener {

	public static final String INTENT_DISCOUNT_ID = "discountid";
	public static final String INTENT_SHOP_ID = "shopid";
	public static final String INTENT_SHOP_NAME = "shopname";

	private String mDiscountId;
	private String mShopId;
	private String mShopName;
	private DiscountDetail mDiscountDetail;

	private VerticalScrollView mSrollView;

	private View mHead;
	private View mviewpager;
	private int mHeight = 0;

	RequestQueue mQueue;
	ImageLoader mImageLoader;

	private RYHttpResponseHandler mFavoriteHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			try {
				Model model = (Model) o;
				if (model != null && model.errno == 0) {
					ImageView img = (ImageView) findViewById(R.id.img_favorite);
					img.setSelected(!img.isSelected());
					showLoading(false, null);
				} else {
					onFailure();
				}
			} catch (Exception e) {
				onFailure(e);
			}
		}

		private void onFailure() {
			showLoading(false, null);
			showToast("操作失败");
		}

		@Override
		public void onFailure(Throwable throwable) {
			onFailure();
		}
	};

	private OnClickListener mClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			boolean favorite = findViewById(R.id.img_favorite).isSelected();
			showLoading(true, "加载中");
			if (favorite) {
				RYHttpClient.delFavorite(DiscountDetailActivity.this,
						mFavoriteHandler, LoginHelper.getInstance().getBDUSS(),
						mDiscountId);
			} else {
				RYHttpClient.submitFavorite(DiscountDetailActivity.this,
						mFavoriteHandler, LoginHelper.getInstance().getBDUSS(),
						mDiscountId);
			}
		}
	};

	private RYHttpResponseHandler mHttpResponseHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			// try {
			DiscountDetail detail = (DiscountDetail) o;
			mDiscountDetail = detail;
			onLoadingDataFinished(detail != null, detail);
			// } catch (Exception e) {
			// onLoadingDataFinished(false, null);
			// }
		}

		@Override
		public void onFailure(Throwable throwable) {
			onLoadingDataFinished(false, null);
		}
	};

	public static void startDiscountDetailActivity(Context context, String id) {
		if (context == null || TextUtils.isEmpty(id)) {
			return;
		}
		Intent intent = new Intent(context, DiscountDetailActivity.class);
		intent.putExtra(INTENT_DISCOUNT_ID, id);
		context.startActivity(intent);
	}

	private void showToast(String msg) {
		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
	}

	private void showLoading(boolean show, String msg) {
		if (isFinishing()) {
			return;
		}
		if (show) {
			findViewById(R.id.layout_loading).setVisibility(View.VISIBLE);
			((TextView) findViewById(R.id.text_loading)).setText(msg);
		} else {
			findViewById(R.id.layout_loading).setVisibility(View.GONE);
		}
	}

	private void onLoadingDataStarted(String id, double lat, double lon) {
		showLoading(true, "加载中");
		RYHttpClient.getDiscountDetail(this, mHttpResponseHandler, id,
				LoginHelper.getInstance().getBDUSS(), lat, lon);
	}

	private void onLoadingDataFinished(boolean succeed, DiscountDetail detail) {
		System.out.println("DiscountDetailActivity.onLoadingDataFinished()");
		if (succeed && detail != null) {
			loadViews(detail);
		} else {
			showToast("加载失败！");
		}
		showLoading(false, "");
	}

	private void loadViews(final DiscountDetail detail) {
		// if (!TextUtils.isEmpty(detail.picurl)) {
		// ((NetworkImageView) findViewById(R.id.image)).setImageUrl(
		// detail.picurl, mImageLoader);
		// ((NetworkImageView) findViewById(R.id.image))
		// .setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// startActivity(new Intent(
		// DiscountDetailActivity.this,
		// ShopAlbumActivity.class).putExtra(
		// INTENT_SHOP_ID, mShopId).putExtra(
		// INTENT_SHOP_NAME, mShopName));
		// }
		// });
		// }
		LinearLayout content = (LinearLayout) findViewById(R.id.layout_content);

		if (detail.list != null && detail.list.size() > 0) {
			for (DetailItem item : detail.list) {
				View child = null;
				if (item != null && !TextUtils.isEmpty(item.type)) {
					if ("youhui".equals(item.type)) {
						child = content.findViewById(R.id.view_youhui);
						child.setVisibility(View.VISIBLE);

						if (!TextUtils.isEmpty(item.originalprice)) {
							((TextView) child
									.findViewById(R.id.text_original_price))
									.setText("价值￥" + item.originalprice);
							((TextView) mHead
									.findViewById(R.id.text_original_price_head))
									.setText("价值￥" + item.originalprice);
						}
						if (!TextUtils.isEmpty(item.presentprice)) {
							((TextView) child.findViewById(R.id.text_price))
									.setText("￥" + item.presentprice);
							((TextView) mHead
									.findViewById(R.id.text_price_head))
									.setText("￥" + item.presentprice);
						}
						((TextView) child.findViewById(R.id.text_name))
								.setText(item.title);
						((TextView) child.findViewById(R.id.text_content))
								.setText(item.content);
						((TextView) child.findViewById(R.id.text_num))
								.setText(item.signup + "人购买");
						((TextView) child.findViewById(R.id.text_time))
								.setText(item.endtime);
						final DocIndicator docIndicator = (DocIndicator) findViewById(R.id.indicator);
						if (docIndicator != null) {
							docIndicator.setTotal(item.pic4app.size());
							docIndicator.setCurrent(0);
						}
						ViewPager vp = (ViewPager) findViewById(R.id.viewpager);
						vp.setPageMargin(80);
						vp.setOnPageChangeListener(new OnPageChangeListener() {

							@Override
							public void onPageSelected(int arg0) {
								if (docIndicator != null) {
									docIndicator.setCurrent(arg0);
								}
							}

							@Override
							public void onPageScrolled(int arg0, float arg1,
									int arg2) {

							}

							@Override
							public void onPageScrollStateChanged(int arg0) {

							}
						});
						ArrayList<PhotoItem> mData = new ArrayList<PhotoItem>();
						for (int i = 0; i < item.pic4app.size(); i++) {
							String s = item.pic4app.get(i);
							PhotoItem photo = new PhotoItem();
							photo.picurl = s;
							mData.add(photo);
						}
						vp.setAdapter(new ImageFragmentPagerAdapter(
								getSupportFragmentManager(), mData));
						vp.setCurrentItem(0);

					} else if ("shopinfo".equals(item.type)) {
						mShopId = item.shopid;
						mShopName = item.shopname;
						if (TextUtils.isEmpty(LoginHelper.getInstance()
								.getBDUSS())) {
							findViewById(R.id.img_favorite).setVisibility(
									View.GONE);
						} else {
							findViewById(R.id.img_favorite).setVisibility(
									View.VISIBLE);
							findViewById(R.id.img_favorite).setSelected(
									item.favorite == 1);
							findViewById(R.id.img_favorite).setOnClickListener(
									mClickListener);
						}
						child = content.findViewById(R.id.view_shopinfo);
						child.setVisibility(View.VISIBLE);
						if (!TextUtils.isEmpty(item.shopname)) {
							((TextView) child.findViewById(R.id.text_shopname))
									.setText(item.shopname);
						}
						((ImageView) child.findViewById(R.id.score))
								.setImageLevel(item.score);
						if (!TextUtils.isEmpty(item.address)) {
							((TextView) child.findViewById(R.id.text_address))
									.setText(item.address);
						}
						final String phoneNumber = item.tele;
						child.findViewById(R.id.phone).setOnClickListener(
								new OnClickListener() {

									@Override
									public void onClick(View v) {
										onPhoneCallClicked(phoneNumber);
									}
								});
					} else if ("activedetail".equals(item.type)) {
						child = content.findViewById(R.id.view_activedetail);
						child.setVisibility(View.VISIBLE);
						((TextView) child.findViewById(R.id.content))
								.setText(item.content);
						for (int i = 0; i < item.pics.size(); i++) {
							addImages(item.pics.get(i), (ViewGroup) child);
						}
					} else if ("notice".equals(item.type)) {
						child = content.findViewById(R.id.view_notice);
						child.setVisibility(View.VISIBLE);
						((TextView) child.findViewById(R.id.content))
								.setText(item.content);
					}
				}
			}
		}
	}

	private void addImages(String picurl, ViewGroup mBody) {
		View v = LayoutInflater.from(this).inflate(
				R.layout.view_activity_detail, mBody, false);
		((NetworkImageView) v.findViewById(R.id.image)).setImageUrl(picurl,
				mImageLoader);
		mBody.addView(v);
	}

	@Override
	public void onScrollChanged(int l, int t, int oldl, int oldt) {
		System.out.println(l + " " + t);
		if (t > 0) {
			if (mHeight <= 0) {
				mHeight = mviewpager.getHeight();
			}
			if (mHeight > 0) {
				if (t > mHeight) {
					mHead.setVisibility(View.VISIBLE);
				} else {
					mHead.setVisibility(View.GONE);
				}
			}
		} else {
			mHead.setVisibility(View.GONE);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_discount_detail);

		mviewpager = findViewById(R.id.viewpager);
		mHead = findViewById(R.id.layout_head);
		mSrollView = (VerticalScrollView) findViewById(R.id.scrollview);
		mSrollView.setOnScrollChangedListener(this);

		mQueue = Volley.newRequestQueue(DiscountDetailActivity.this);
		mImageLoader = new ImageLoader(mQueue, new BitmapLruCache());
		findViewById(R.id.img_icon).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
		findViewById(R.id.button_report).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (Config
								.isShopManagerVersionAndNotBinded(DiscountDetailActivity.this)) {
							showToast("您未绑定会员账号，请绑定后再使用此功能");
						} else {

							if (!LoginHelper.getInstance().ensureLogin(
									DiscountDetailActivity.this)) {
								return;
							}

							startActivity(new Intent(
									DiscountDetailActivity.this,
									ShopErrorReportActivity.class).putExtra(
									INTENT_SHOP_ID, mShopId).putExtra(
									INTENT_SHOP_NAME, mShopName));
						}

					}
				});
		findViewById(R.id.btn_baoming).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (!LoginHelper.getInstance().ensureLogin(
								DiscountDetailActivity.this)) {
							return;
						}

						ReservationOldActivity
								.startActivityReservationActivity(
										DiscountDetailActivity.this,
										mDiscountId);
					}
				});
		mHead.findViewById(R.id.btn_baoming_head).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (!LoginHelper.getInstance().ensureLogin(
								DiscountDetailActivity.this)) {
							return;
						}

						ReservationOldActivity
								.startActivityReservationActivity(
										DiscountDetailActivity.this,
										mDiscountId);
					}
				});
		findViewById(R.id.button_upload).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (Config
								.isShopManagerVersionAndNotBinded(DiscountDetailActivity.this)) {
							showToast("您未绑定会员账号，请绑定后再使用此功能");
						} else {

							if (!LoginHelper.getInstance().ensureLogin(
									DiscountDetailActivity.this)) {
								return;
							}

							startActivity(new Intent(
									DiscountDetailActivity.this,
									UploadPhotoActivity.class).putExtra(
									INTENT_SHOP_ID, mShopId).putExtra(
									INTENT_SHOP_NAME, mShopName));
						}

					}
				});
		findViewById(R.id.button_signin).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (Config
								.isShopManagerVersionAndNotBinded(DiscountDetailActivity.this)) {
							showToast("您未绑定会员账号，请绑定后再使用此功能");
						} else {

							if (!LoginHelper.getInstance().ensureLogin(
									DiscountDetailActivity.this)) {
								return;
							}

							startActivity(new Intent(
									DiscountDetailActivity.this,
									ShopAddRegistrationActivity.class)
									.putExtra(INTENT_SHOP_ID, mShopId)
									.putExtra(INTENT_SHOP_NAME, mShopName));
						}

					}
				});
		findViewById(R.id.button_remark).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (Config
								.isShopManagerVersionAndNotBinded(DiscountDetailActivity.this)) {
							showToast("您未绑定会员账号，请绑定后再使用此功能");
						} else {

							if (!LoginHelper.getInstance().ensureLogin(
									DiscountDetailActivity.this)) {
								return;
							}

							startActivity(new Intent(
									DiscountDetailActivity.this,
									ShopAddRemarkActivity.class).putExtra(
									INTENT_SHOP_ID, mDiscountId).putExtra(
									INTENT_SHOP_NAME, ""));
						}

					}
				});
		findViewById(R.id.img_favorite).setOnClickListener(mClickListener);
		mDiscountId = getIntent().getStringExtra(INTENT_DISCOUNT_ID);
		if (TextUtils.isEmpty(mDiscountId)) {
			finish();
			return;
		}
		onLoadingDataStarted(mDiscountId, Config.sMyLocation.getLatitude(),
				Config.sMyLocation.getLongitude());
	}

	private void onPhoneCallClicked(String phoneNumber) {
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");
		if (prev != null) {
			return;
		}
		ft.addToBackStack(null);

		// Create and show the dialog.
		DialogFragment newFragment = PickPhoneCallFragment.newInstance(
				UIUtils.findPhoneNumbers(phoneNumber), mShopId);
		newFragment.show(ft, "dialog");
	}

	private void onShowMap(double lat, double lon, String name) {
		try {
			Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:"
					+ lat + "," + lon + "?q=" + lat + "," + lon + "(" + name
					+ ")"));
			startActivity(intent);
		} catch (ActivityNotFoundException e) {
			Intent browserIntent = new Intent(Intent.ACTION_VIEW,
					Uri.parse("http://api.map.baidu.com/marker?location=" + lat
							+ "," + lon + "&title=" + name + "&output=html"));
			startActivity(browserIntent);
		}
	}

	/**
	 * Image pager adapter which uses fragment as a container.
	 * 
	 * @author laiwenjie
	 * @date 2012-9-10
	 * 
	 */
	private class ImageFragmentPagerAdapter extends FragmentStatePagerAdapter {
		private ArrayList<PhotoItem> mData;

		public ImageFragmentPagerAdapter(FragmentManager fm,
				ArrayList<PhotoItem> data) {
			super(fm);
			mData = data;
		}

		@Override
		public int getCount() {
			return mData.size();
		}

		@Override
		public Fragment getItem(int position) {
			return ImageFragment.newInstance(mData.get(position));
		}
	}

	/**
	 * Detail image fragment
	 * 
	 * @author laiwenjie
	 * @date 2012-9-10
	 * 
	 */
	public static class ImageFragment extends Fragment {
		public static final String IMAGE_DATA = "image_data";

		private PhotoItem data;

		public static ImageFragment newInstance(PhotoItem data) {
			ImageFragment fragment = new ImageFragment();

			Bundle b = new Bundle();
			b.putSerializable(IMAGE_DATA, data);

			fragment.setArguments(b);

			return fragment;
		}

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);

			if (getArguments() != null) {
				data = (PhotoItem) getArguments().getSerializable(IMAGE_DATA);
			}
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			return inflater.inflate(R.layout.view_image, container, false);
		}

		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);

			View view = getView();

			RequestQueue mQueue = Volley.newRequestQueue(getActivity());
			ImageLoader mImageLoader = new ImageLoader(mQueue,
					new BitmapLruCache());
			if (!TextUtils.isEmpty(data.picurl)) {
				((NetworkImageView) view.findViewById(R.id.picture))
						.setImageUrl(data.picurl, mImageLoader);
			}
		}

		@Override
		public void onDestroyView() {
			super.onDestroyView();
		}
	}
}
